<!DOCTYPE html>
<html>

<head>
    <meta charset="utf-8">
    <meta name="viewport"
        content="width=device-width, height=device-height, user-scalable=no, initial-scale=1.0, minimum-scale=1.0, maximum-scale=1.0">
    <meta name="format-detection" content="telephone=no">
    <title>在线客服</title>
    <script type="text/javascript" src="../mobile/js/plugin/jquery-1.10.1.min.js"></script>
    <link rel="stylesheet" href="../mobile/js/layim/dist/css/layui.mobile.css" />
    <link rel="stylesheet" href="../mobile/css/font-awesome.min.css" />
    <script src="../mobile/js/layim/dist/layui.js"></script>

    <style>
        .navRightBtn {
            display: none;
        }

        .layim-title {
            /* background: -webkit-gradient(linear, 0 0, 100% 0, from(#907e3f), to(#d4b072)) !important;
            background: -webkit-linear-gradient(left, #907e3f, #d4b072) !important;
            background: -moz-linear-gradient(left, #907e3f, #d4b072) !important;
            background: -o-linear-gradient(left, #907e3f, #d4b072) !important;
            background: linear-gradient(left, #907e3f, #d4b072) !important; */
            background: #0081ff !important;
            height: 44px !important;
            line-height: 44px !important;
            font-size: 16px !important;
        }

        .layim-chat-footer {
            display: flex;
            position: fixed;
            bottom: 0;
            left: 10px;
            right: 10px;
            width: 100%;
            left: 0 !important;
            padding: 10px !important;
            box-sizing: border-box !important;
            background: #fff !important;
            height: 60px !important;
        }

        .layim-chat-tool {
            width: 58px;
        }

        .layim-chat-send {
            width: 100% !important;
        }

        .layim-chat-send button {
            white-space: nowrap;
            background-color: #63d4f0 !important;
            position: static;
            right: 0;
            z-index: 9;
            width: 11px;
            padding: 0 !important;
            width: 60px;
            display: none;
        }

        .layim-chat-tool {
            width: 40% !important;
            justify-content: space-evenly;
            display: flex;

        }

        .layim-chat-send input {
            border: 1px #ddd solid !important;
        }

        .layim-chat-mine .layim-chat-text {
            background-color: #d4b072 !important;
        }

        .layim-chat-mine .layim-chat-text:after {
            border-top-color: #d4b072 !important;
        }

        .layui-m-layermain,
        .layui-m-layershade,
        .layim-panel,
        .layim-chat-main,
        .layim-content,
        .layim-chat-footer {
            position: absolute;
        }

        .layim-chat-tool span {
            position: relative;
            margin: 0 15px;
            display: inline-block;
            vertical-align: top;
            font-size: 28px;
            cursor: pointer;
            width: 30px;
            margin: 0 !important;
            padding: 0 0px;
            color: #666;
        }

    </style>
</head>

<body>
    <script>
        (function ($) {
            $.getUrlParam = function (name) {
                var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");
                var r = window.location.search.substr(1).match(reg);
                if (r != null)
                    return decodeURI(r[2]); // decodeURI(r[2]); 解决参数是中文时的乱码问题

                return null;
            }
        })(jQuery);

        var imgUploadUrl = ""; //图片上传
        console.log(localStorage.getItem('user'));
        //本人
        var from_id = $.getUrlParam('from_id');
        var name = "";
        var avatar = "";
        var phone = '';
        //对象
        var kid = "k001";
        var k_name = '客服';
        var k_avatar = "http://106.12.213.63/robot/public/public/mobile/img/icon_10.png";

        // var host = "http://localhost/robot/public/";
        var host = 'http://106.12.213.63/robot/public/';
        var ajaxUrl = host + '/api/users/user';
        var token = localStorage.getItem('token');
        $.ajax({
            type: "get",
            dataType: "json",
            async: false,
            url: host + 'api/app/users/user',
            data: {
                user_id: $.getUrlParam('from_id')
            },
            success: function (res) {
                if (res.code == 200) {
                    from_id = res.data.id;
                    name = res.data.nickname;
                    if (res.data.avatar == null) {
                        avatar = 'http://106.12.213.63/robot/public/mobile/img/defaultAvatar.png'
                    } else {
                        avatar = res.data.avatar;
                    }
                    phone = res.data.nickname + '-' + res.data.username;
                } else if (res.code == 401) {
                    localStorage.removeItem("token");
                    window.location.href = "login.html";
                }

            },
        });

    </script>
    <script>
        layui.config({
            version: true
        }).use('mobile', function () {
            var mobile = layui.mobile,
                layim = mobile.layim,
                layer = mobile.layer;
            // var socket = new WebSocket('ws://192.168.1.43:2000');
            var socket = new WebSocket('ws://106.12.213.63:9501');
            //演示自动回复
            /* var autoReplay = [
               '您好，我现在有事不在，一会再和您联系。',
               '你没发错吧？face[微笑] ',
               '洗澡中，请勿打扰，偷窥请购票，个体四十，团体八折，订票电话：一般人我不告诉他！face[哈哈] ',
               '你好，我是主人的美女秘书，有什么事就跟我说吧，等他回来我会转告他的。face[心] face[心] face[心] ',
               'face[威武] face[威武] face[威武] face[威武] ',
               '<（@￣︶￣@）>',
               '你要和我说话？你真的要和我说话？你确定自己想说吗？你一定非说不可吗？那你说吧，这是自动回复。',
               'face[黑线]  你慢慢说，别急……',
               '(*^__^*) face[嘻嘻] ，是贤心吗？'
             ];*/

            layim.config({
                //上传图片接口
                //  uploadImage: {
                //    url: imgUploadUrl//（返回的数据格式见下文）
                //    ,type: 'post' //默认post
                //  },

                //上传文件接口
                /*,uploadFile: {
                  url: '/upload/file' //（返回的数据格式见下文）
                  ,type: '' //默认post
                }*/
                brief: true,
                init: {
                    //我的信息
                    mine: {
                        "username": name, //我的昵称
                        "id": from_id, //我的ID
                        avatar: avatar
                    },
                    //我的好友列表
                    friend: []
                }

                //扩展聊天面板工具栏
                /*,tool: [{
                  alias: 'code'
                  ,title: '代码'
                  ,iconUnicode: '&#xe64e;'
                }]*/

                //扩展更多列表
                /*,moreList: [{
                  alias: 'find'
                  ,title: '发现'
                  ,iconUnicode: '&#xe628;' //图标字体的unicode，可不填
                  ,iconClass: '' //图标字体的class类名
                },{
                  alias: 'share'
                  ,title: '分享与邀请'
                  ,iconUnicode: '&#xe641;' //图标字体的unicode，可不填
                  ,iconClass: '' //图标字体的class类名
                }]*/

                //,tabIndex: 1 //用户设定初始打开的Tab项下标
                //,isNewFriend: false //是否开启“新的朋友”
                //,isgroup: true //是否开启“群聊”
                //,chatTitleColor: '#c00' //顶部Bar颜色
                //,title: 'LayIM' //应用名，默认：我的IM
            });

            /* var wsUri ="ws://echo.websocket.org/";
               var webSocket = new WebSocket(wsUri);*/
            //alert(socket.readyState)

            //socket.send('Hi Server, I am LayIM!');

            //连接成功时触发
            socket.onopen = function () {

            };
            //监听收到的消息
            socket.onmessage = function (res) {
                var obj = JSON.parse(res.data);
                var obj2 = {
                    content: obj.data,
                    username: obj.username,
                    id: kid, //聊天窗id
                    type: obj.type,
                    avatar: obj.avatar
                }
                if (obj.type == 'init') {
                    var params = {
                        "from_id": from_id,
                    };
                    var ajaxUrl = host + 'api/chat/load';
                    $.post(ajaxUrl, params, function (res) {
                        $.each(res.data, function (i, e) {
                            //对象
                            var obj2 = {
                                avatar: e.from_avatar,
                                content: e.content,
                                username: e.from_name,
                                id: e.from_id, //聊天窗id
                                type: 'friend'
                            }
                            obj2.mine = false;
                            layim.getMessage(obj2);
                        })
                    })

                    var msg = {
                        from_id: from_id,
                        type: 'bind'
                    }
                    console.log(obj);
                    socket.send(JSON.stringify(msg));
                } else if (obj.type == 'say') {
                    obj2.type = 'friend';
                    obj2.mine = false;
                    console.log(obj);
                    layim.getMessage(obj2);
                } else if (obj.type == 'save') {
                    //入库
                    var params = {
                        "from_id": obj.from_id,
                        "to_id": obj.to_id,
                        "is_read": obj.isRead,
                        "content": obj.data,
                        'from_name': phone,
                        'from_avatar': avatar,
                    };
                    $.ajax({
                        type: "post",
                        dataType: "json",
                        async: false,
                        url: host + 'api/chat/save',
                        data: params,
                        headers: {
                            'token': token
                        },
                        success: function (res) {

                        },
                    });

                }
                //     else if(obj.type == 'save'){
                //     //入库
                //     var url = 'http://192.168.40.128/save.php';
                //     var data = {"from_id":obj.from_id,"to_id":obj.to_id,"isRead":obj.isRead,"content":obj.data};
                //     $.post(url,data,function (data,status) {
                //     })
                // }
                else {

                }

                //res为接受到的值，如 {"emit": "messageName", "data": {}}
                //emit即为发出的事件名，用于区分不同的消息
            };

            socket.onerror = function () {
                console.log("onerror")
            };

            socket.onclose = function (res) {
                console.log("onclose")
            };

            layim.chat({
                name: "在线客服" //名称
                    ,
                type: 'friend' //聊天类型
                    ,
                avatar: k_avatar,
                id: kid //好友id
            });

            //创建一个会话
            /*
            layim.chat({
              id: 111111
              ,name: '许闲心'
              ,type: 'kefu' //friend、group等字符，如果是group，则创建的是群聊
              ,avatar: 'http://tp1.sinaimg.cn/1571889140/180/40030060651/1'
            });
            */

            //监听点击“新的朋友”
            /*  layim.on('newFriend', function(){
                layim.panel({
                  title: '新的朋友' //标题
                  ,tpl: '<div style="padding: 10px;">自定义模版，{{d.data.test}}</div>' //模版
                  ,data: { //数据
                    test: '么么哒'
                  }
                });
              });*/

            //查看聊天信息
            /*  layim.on('detail', function(data){
                //console.log(data); //获取当前会话对象
                layim.panel({
                  title: data.name + ' 聊天信息' //标题
                  ,tpl: '<div style="padding: 10px;">自定义模版，<a href="http://www.layui.com/doc/modules/layim_mobile.html#ondetail" target="_blank">参考文档</a></div>' //模版
                  ,data: { //数据
                    test: '么么哒'
                  }
                });
              });*/

            //监听点击更多列表
            /* layim.on('moreList', function(obj){
               switch(obj.alias){
                 case 'find':
                   layer.msg('自定义发现动作');

                   //模拟标记“发现新动态”为已读
                   layim.showNew('More', false);
                   layim.showNew('find', false);
                 break;
                 case 'share':
                   layim.panel({
                     title: '邀请好友' //标题
                     ,tpl: '<div style="padding: 10px;">自定义模版，{{d.data.test}}</div>' //模版
                     ,data: { //数据
                       test: '么么哒'
                     }
                   });
                 break;
               }
             });*/

            //监听返回
            //layim.on('back', function() {
            //history.back();
            /*layer.open({
            	type:2
            });*/
            //layer.load();
            /*setTimeout(function() {
            	location.href = "{php echo mobileUrl('pc.cms_doctor.mobile')}" + "&page=jumpFaq";
            }, 1000)*/

            //history.back();
            //window.location.href="{php echo mobileUrl('pc.cms_doctor.mobile')}";
            //如果你只是弹出一个会话界面（不显示主面板），那么可通过监听返回，跳转到上一页面，如：history.back();
            //});

            //监听自定义工具栏点击，以添加代码为例
            /*layim.on('tool(code)', function(insert, send){
              insert('[pre class=layui-code]123[/pre]'); //将内容插入到编辑器
              send();
            });*/

            $(".layim-chat-back").removeAttr("layim-event");
            //返回
            $(".layim-chat-back").bind("click", function () {
                //parent.chatBack();
                // history.back();
                window.history.go(-1);
            });

            //监听发送消息
            layim.on('sendMessage', function (data) {
                $(".layim-chat-send button").hide();

                var To = data.to;
                var mine = data.mine;
                var msg = {
                    type: 'say',
                    avatar: avatar,
                    from_id: from_id,
                    to_id: kid,
                    username: phone,
                    name: '健康咨询',
                    text: mine.content
                }
                socket.send(JSON.stringify(msg));
                //console.log(data);

                //演示自动回复
                /*setTimeout(function(){
                  var obj = {};
                  if(To.type === 'group'){
                    obj = {
                      username: '模拟群员'+(Math.random()*100|0)
                      ,avatar: layui.cache.dir + 'images/face/'+ (Math.random()*72|0) + '.gif'
                      ,id: To.id
                      ,type: 'group'
                      ,content: autoReplay[Math.random()*9|0]
                    }
                  } else {
                    obj = {
                      username: To.name
                      ,avatar: To.avatar
                      ,id: To.id
                      ,type: To.type
                      ,content: autoReplay[Math.random()*9|0]
                    }
                  }
                  layim.getMessage(obj);
                }, 3000);*/
            });

            $(function () {
                /*var clientHeight = document.documentElement.clientHeight || document.body.clientHeight;
			        $(window).on("resize",function(){
			            var nowClientHeight = document.documentElement.clientHeight || document.body.clientHeight;
			            if (clientHeight > nowClientHeight) {
			                var focus=$(".layim-chat-send input:focus");
			                var offset =focus.offset();
			                if(nowClientHeight/2<offset.top){
			                    var top=nowClientHeight/2-offset.top;
			                }
			                $(".layim-panel").css('top',top);
			                //键盘弹出的事件处理     x  -x
			                //$("footer").hide();
			            }
			            else {
			                //键盘收起的事件处理
			               // $("footer").show();
			                $(".layim-panel").css('top',0);
			            }

			        });*/






                //解决手机软键盘遮住input方法
                /*$(".layim-chat-send input").on("click", function() {
                	var target = this;
                	setTimeOut(function() {
                		target.scrollIntoView(true);
                	}, 300);
                })*/
                //输入框聚焦
                /*$(".layim-chat-send input").focus(function(){
                	var target = this;
                	setTimeout(function() {
                		// 设置body的高度为可视高度+302
                		// 302为原生键盘的高度
                		//$(".layim-chat-send input").onfocus();
                		//$(".layim-chat-footer").css({"top":50,"bottom":"auto"});
                		document.getElementsByTagName('body')[0].style.height = (window.innerHeight + 402) + 'px';
                		document.body.scrollTop = 402;
                		//target.scrollIntoView(true);
                	}, 300)
                });

                //输入框失焦
                $(".layim-chat-send input").blur(function(){
                	var target = this;
                	document.getElementsByTagName('body')[0].style.height = window.innerHeight + 'px';


                	//target.scrollIntoView(true);
                });*/


                //实时监听输入框
                $('.layim-chat-send input').bind('input propertychange', function () {
                    var con = $(this).val();
                    if ($.trim(con) != "") {
                        $(".layim-chat-send button").show();
                    } else {
                        $(".layim-chat-send button").hide();
                    }
                });

            })
            //模拟收到一条好友消息
            /*setTimeout(function(){
              layim.getMessage(
                  {
                username: "俊男"
                ,avatar: "http://tp1.sinaimg.cn/1571889140/180/40030060651/1"
                ,id: "100001"
                ,type: "friend"
                ,cid: Math.random()*100000|0 //模拟消息id，会赋值在li的data-cid上，以便完成一些消息的操作（如撤回），可不填
                ,content: "你好"
              });
            }, 3000);*/

            //监听查看更多记录
            /* layim.on('chatlog', function(data, ul){
               console.log(data);
               layim.panel({
                 title: '与 '+ data.name +' 的聊天记录' //标题
                 ,tpl: '<div style="padding: 10px;">这里是模版，{{d.data.test}}</div>' //模版
                 ,data: { //数据
                   test: 'Hello'
                 }
               });
             });*/

        });

    </script>
    <script>
        //获取url中的参数
        function getUrlParam(name) {
            var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)"); //构造一个含有目标参数的正则表达式对象
            var r = window.location.search.substr(1).match(reg); //匹配目标参数
            if (r != null) return unescape(r[2]);
            return null; //返回参数值
        }

    </script>
</body>

</html>
